//引入各种插件
const HtmlWebpackPlugin = require("html-webpack-plugin"); //引入html插件
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); //引入css提取插件
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin"); //压缩css的插件

//根据页面数自动生成js入口和html入口
const glob = require("glob");
let js = glob.sync("./src/pages/*/*.js");
let entryObj = {};
js.forEach((v) => {
	let fn = v.split("/").pop().replace(".js", "");
	entryObj[fn] = v;
});

let html = glob.sync("./src/pages/*/*.html");
let htmlArr = [];
html.forEach((v) => {
	let filename = v.split("/").pop();
	let name = filename.replace(".html", "");
	htmlArr.push(
		new HtmlWebpackPlugin({
			template: v, //设置html文件的入口
			filename: filename, //设置出口
			chunks: [name], //设置html中加载哪些模块
		})
	);
});

//webpack的配置文件
module.exports = {
	//多入口
	entry: entryObj,

	//多出口
	output: {
		filename: "js/[name].js",
		path: __dirname + "/dist",
		publicPath: "./", //公共资源路径
	},

	//加载器
	module: {
		rules: [
			//css加载器
			{
				test: /\.css$/i,
				use: [
					{
						loader: MiniCssExtractPlugin.loader,
						options: {
							publicPath: "../",
						},
					},
					"css-loader",
				],
			},

			//less加载器
			{
				test: /\.less$/i,
				use: [
					{
						loader: MiniCssExtractPlugin.loader,
						options: {
							publicPath: "../",
						},
					},
					"css-loader",
					"less-loader",
				],
			},

			//图片加载器
			{
				test: /\.(jpg|png|gif|webp|jpeg)$/i,
				loader: "url-loader",
				options: {
					limit: 8 * 1024, //8Kb以下打包成代码，8Kb以上打包成文件
					name: "[hash:8].[ext]", //设置打包后的文件名
					outputPath: "imgs", //设置输出文件的路径
					esModule: false, //关闭ES6的模块化
				},
			},

			//html加载器
			{ test: /\.html$/i, use: ["html-loader"] },

			//字体图标加载器
			{
				test: /\.(ttf|woff|woff2|eot|svg)$/i,
				loader: "file-loader",
				options: {
					name: "[hash:16].[ext]",
					outputPath: "fonts",
					esModule: false,
				},
			},
		],
	},

	//插件
	plugins: [
		//html插件
		...htmlArr,

		//提取css插件
		new MiniCssExtractPlugin({
			filename: "css/[name].css",
		}),

		//压缩css插件
		new OptimizeCssAssetsWebpackPlugin(),
	],

	//模式 development开发模式，production生产模式
	mode: process.env.NODE_ENV,

	//开发服务器
	devServer: {
		contentBase: __dirname + "/dist", // 启动服务器目录
		compress: true, // 启动gzip
		port: 8080, // 端口
		open: true, // 自动打开服务
		publicPath: "/", // 静态资源查找路径
		openPage: "index.html", // 打开的页面
	},
};
